package com.kczd.jinlan.myview;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.kczd.jinlan.R;
import com.kczd.jinlan.adapter.MyExpandableListViewAdapter;
import com.kczd.jinlan.adapter.normaladapter.SearchAdapter;
import com.kczd.jinlan.db.RecordSQLiteOpenHelper;
import com.kczd.jinlan.fragment.ShopPingFragment;
import com.kczd.jinlan.model.Classify;
import com.kczd.jinlan.utils.ListSharedUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * zhangy
 * Created by Carson_Ho on 16/11/15.
 */
public class Search_View extends LinearLayout implements View.OnClickListener{

    private Context context;
    private List<String> data=new ArrayList<>();

    /*UI组件*/
    public static EditText et_search;
    private TextView tv_tip,mHorstory;
    private GridView gridView_search_hostory;

    /*列表及其适配器*/
    private Search_Listview listView;
    private BaseAdapter adapter;

    /*数据库变量*/
    private RecordSQLiteOpenHelper helper ;
    private SQLiteDatabase db;

    /*
       数据封装ExpandableListView
     */
    private ExpandableListView expandableListView;
    private List<String> mDatas_jiazheng = new ArrayList<>(Arrays.asList("土豆", "黄瓜", "小白菜","茄子","豆芽","豆腐","葱花","小米"));
    private List<String> mDatas_jiaoyu = new ArrayList<>(Arrays.asList("苹果", "鸭梨", "葡萄","哈密瓜","红提子","青提子","驴蹄子","马蹄子"));
    private List<String> mDatas_liren = new ArrayList<>(Arrays.asList("大鱼", "小鱼", "海带","带鱼","虾米","螃蟹","娃娃鱼","鲤鱼"));
    private List<String> mDatas_xiuxian = new ArrayList<>();
    private List<String> mDatas_yundong = new ArrayList<>();
    private List<String> mDatas_meishi = new ArrayList<>();
    private List<String> mDatas_hua = new ArrayList<>();
    private List<String> mDatas_shi = new ArrayList<>();

    /**
     * 每个分组的名字的集合
     */
    private List<Classify> groupList;

    /**
     * 所有分组的所有子项的 GridView 数据集合
     */
    private List<List<String>> itemList=new ArrayList<>();


    /*三个构造函数*/
    //在构造函数里直接对搜索框进行初始化 - init()
    public Search_View(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public Search_View(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public Search_View(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init();
    }

    /*初始化搜索框*/
    private void init(){

        //初始化UI组件
        initView();


        //实例化数据库SQLiteOpenHelper子类对象
        helper = new RecordSQLiteOpenHelper(context);

        //搜索框的文本变化实时监听
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                  if(s!=null){
                      queryData(s+"");
                  }
            }

            //输入后调用该方法
            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString().trim().length() == 0) {
                    //若搜索框为空,则模糊搜索空字符,即显示所有的搜索历史
                    tv_tip.setVisibility(View.VISIBLE);
                    listView.setAdapter(null);
                }else{
                    tv_tip.setVisibility(View.GONE);
                }
            }
        });


        // 搜索框的键盘搜索键
        // 点击回调
        et_search.setOnKeyListener(new OnKeyListener() {// 输入完后按键盘上的搜索键

            // 修改回车键功能
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    boolean hasData = hasData(et_search.getText().toString().trim());
                    if (!hasData) {
                        Toast.makeText(context, "未查到相关数据", Toast.LENGTH_SHORT).show();
                    }else {
                        //根据输入的内容模糊查询商品，并跳转到另一个界面，这个需要根据需求实现
                        Toast.makeText(context, "点击搜索", Toast.LENGTH_SHORT).show();
                    }

                }
                return false;
            }
        });

        //列表监听
        //即当用户点击搜索历史里的字段后,会直接将结果当作搜索字段进行搜索
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                SharedPreferences mySharedPreferences= context.getSharedPreferences("scenelist", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = mySharedPreferences.edit();

                //获取到用户点击列表里的文字,并自动填充到搜索框内
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                et_search.setText(name);
                if(!data.contains(name)) {
                    data.add(name);
                    try {
                        String liststr = ListSharedUtil.SceneList2String(data);
                        edit.putString("searchdata",liststr);
                        edit.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
//                Intent i=new Intent(context, RequestDetailActivity.class);
//                i.putExtra("type",name);
//                context.startActivity(i);
//                et_search.setText("");
//                listView.setAdapter(null);
//                Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 封装的函数
     */

    /*初始化组件*/
    private void initView(){

        LayoutInflater.from(context).inflate(R.layout.search_layout,this);
        et_search = (EditText) findViewById(R.id.et_search);
        tv_tip = (TextView) findViewById(R.id.tv_tip);
        listView = (Search_Listview) findViewById(R.id.listView);
        mHorstory= (TextView) findViewById(R.id.id_delete);
        mHorstory.setOnClickListener(this);
        LinearLayout ll= (LinearLayout) findViewById(R.id.ll_expandid);
        Button yuyin= (Button) findViewById(R.id.imageView5);
        if(EditText_PassWordDisplay.isShowYuyin)//打开语音
        {
            ll.setVisibility(View.GONE);//分类隐藏
            EditText_PassWordDisplay.isShowYuyin=false;
        }else{
            ll.setVisibility(View.VISIBLE);//分类显示
            yuyin.setVisibility(View.GONE);//语音按钮隐藏
        }

        SharedPreferences mySharedPreferences= context.getSharedPreferences("scenelist", Context.MODE_PRIVATE);
        String liststr = mySharedPreferences.getString("searchdata", "");
        try {
            data=ListSharedUtil.String2SceneList(liststr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        gridView_search_hostory= (GridView) findViewById(R.id.search_item_gridview);
        SearchAdapter searchAdapter=new SearchAdapter(data);
        gridView_search_hostory.setAdapter(searchAdapter);
        searchAdapter.notifyDataSetChanged();
        gridView_search_hostory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                String obj= (String) parent.getItemAtPosition(position);
//                Intent intent=new Intent(context,RequestDetailActivity.class);
//                intent.putExtra("type",obj);
//                context.startActivity(intent);
            }
        });


        /**
         * 初始化ExpandableListView
         */
        ClassifyData();
    }


    /*模糊查询数据 并显示在ListView列表上*/
    private void queryData(String tempName) {
        //模糊搜索
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
        // 创建adapter适配器对象,装入模糊搜索的结果
        adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, cursor, new String[] { "name" },
                new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 设置适配器
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    /*检查数据库中是否已经有该条记录*/
    private boolean hasData(String tempName) {
        //从Record这个表里找到name=tempName的id
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.id_delete://删除历史数据
                SharedPreferences mySharedPreferences= context.getSharedPreferences("scenelist", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = mySharedPreferences.edit();
                edit.putString("searchdata","");
                gridView_search_hostory.setAdapter(null);
                edit.commit();
                break;
        }
    }


    /**
     * 分类数据的封装
     */
    private void ClassifyData() {
        expandableListView = (ExpandableListView) findViewById(R.id.id_listview_list);
        expandableListView.setDivider(null);//去除listview的下划线

        // 每个分组下的每个子项的 GridView 数据集合
        itemList.add(mDatas_jiazheng);
        itemList.add(mDatas_jiaoyu);
        itemList.add(mDatas_liren);
        itemList.add(mDatas_xiuxian);
        itemList.add(mDatas_yundong);
        itemList.add(mDatas_meishi);
        itemList.add(mDatas_hua);
        itemList.add(mDatas_shi);

        // 创建适配器
        MyExpandableListViewAdapter adapter = new MyExpandableListViewAdapter(context,
                ShopPingFragment.minelist, itemList);
        expandableListView.setAdapter(adapter);
        // 隐藏分组指示器
        expandableListView.setGroupIndicator(null);
        // 默认展开第一组
        expandableListView.expandGroup(0);
    }
}
